import 'package:audioplayers/audioplayers.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/log_util.dart';

/// 自定义音频播放
///[audioUrl]音频列表
///[isEnabled]是否可以编辑
///[onCallBack]回调
class CustomAudioplayers extends StatefulWidget {
  const CustomAudioplayers({required this.audioUrl, this.onCallBack, super.key, this.isEnabled = true});

  final List<String> audioUrl;

  final bool isEnabled;

  final Function(List<String> audioUrl)? onCallBack;

  @override
  State<CustomAudioplayers> createState() => CustomAudioplayersState();
}

class CustomAudioplayersState extends State<CustomAudioplayers> {
  /// 音频地址
  // List<String> sourceUrl = [];

  /// 播放器列表
  final List<CustomAudio> playerList = [];

  @override
  void initState() {
    super.initState();
    initData();
  }

  /// 初始化数据
  Future<void> initData() async {
    playerList.clear();
    for (var item in widget.audioUrl) {
      // 添加数据到管理列表
      final player = AudioPlayer();
      final CustomAudio customAudio = CustomAudio(audioPlayer: player, sourceUrl: item); // item.contains('http') ? item : Interface.fileUrl + item);
      await player.setSourceUrl(item.contains('http') ? item : Interface.fileUrl + item);
      // 音频时长
      player.onDurationChanged.listen((Duration d) {
        AppLogger.printLog('Max duration: $d');
        if (mounted) {
          setState(() => customAudio.maxDuration = d);
        }
      });
      // 当前播放时长
      player.onPositionChanged.listen((Duration p) {
        AppLogger.printLog('Current position: $p');
        if (mounted) {
          setState(() => customAudio.position = p);
        }
      });
      // 完成事件
      player.onPlayerComplete.listen((_) async {
        customAudio.position = customAudio.maxDuration;
        setState(() {});
      });
      playerList.add(customAudio);
    }
    setState(() {});
  }

  @override
  void dispose() {
    // 释放资源
    for (var item in playerList) {
      audioPlayerDispose(item);
    }
    super.dispose();
  }

  /// 结束释放音频
  Future<void> audioPlayerDispose(CustomAudio item) async {
    if (item.audioPlayer.state == PlayerState.playing) {
      await item.audioPlayer.stop();
    }
    if (item.audioPlayer.state != PlayerState.disposed) {
      await item.audioPlayer.dispose();
    }
  }

  /// 将微秒转为 "00:00" 格式
  String formatMicroseconds(int microseconds) {
    final Duration duration = Duration(microseconds: microseconds);
    final String twoDigitMinutes = duration.inMinutes.remainder(60).toString().padLeft(2, '0');
    final String twoDigitSeconds = duration.inSeconds.remainder(60).toString().padLeft(2, '0');
    return '$twoDigitMinutes:$twoDigitSeconds';
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      child: ListView.separated(
        itemCount: playerList.length,
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemBuilder: (context, index) {
          final customAudio = playerList[index];
          final player = customAudio.audioPlayer;
          final maxDuration = customAudio.maxDuration ?? const Duration();
          final position = customAudio.position ?? const Duration();

          return Container(
            alignment: Alignment.center,
            padding: EdgeInsets.fromLTRB(10.w, 7.w, 0, 7.w),
            decoration: BoxDecoration(
              border: Border.all(
                color: const Color(0xff5C6DFF).withOpacity(0.2),
              ),
              borderRadius: BorderRadius.circular(4.r),
            ),
            child: Row(
              children: [
                SizedBox(
                  width: 30.w,
                  child: Icon(
                    // Icons.play_circle,
                    player.state == PlayerState.playing ? Icons.stop : Icons.play_circle,
                    color: const Color(0xff5C6DFF),
                    size: 25,
                  ),
                ).clickOnce(() async {
                  if (player.state == PlayerState.playing) {
                    await player.pause();
                  } else if (player.state == PlayerState.completed) {
                    await player
                        .play(DeviceFileSource(customAudio.sourceUrl.contains('http') ? customAudio.sourceUrl : Interface.fileUrl + customAudio.sourceUrl));
                  } else {
                    await player.resume();
                  }
                  setState(() {});
                }),
                AppGaps.hGap10,
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'page${index + 1}',
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: const Color(0xff495061),
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                    customAudio.maxDuration != null
                        ? Text(
                            formatMicroseconds(customAudio.maxDuration!.inMicroseconds),
                            style: TextStyle(
                              fontSize: 10.sp,
                              color: const Color(0xffA0A7B5),
                              fontWeight: FontWeight.w400,
                            ),
                          )
                        : Container()
                  ],
                ),
                Expanded(
                  child: Container(
                    margin: EdgeInsets.symmetric(horizontal: 5.w),
                    height: 10.w,
                    decoration: BoxDecoration(
                      // borderRadius: BorderRadius.circular(4.r),
                      color: const Color(0xff5C6DFF).withOpacity(0.2),
                    ),
                    child: (position.inMicroseconds != 0 && maxDuration.inMicroseconds != 0)
                        ? LinearProgressIndicator(
                            value: position.inMicroseconds / maxDuration.inMicroseconds,
                            backgroundColor: Colors.transparent,
                            valueColor: const AlwaysStoppedAnimation<Color>(Colors.blue),
                          )
                        : Container(),
                  ),
                ),
                widget.isEnabled
                    ? SizedBox(
                        width: 30.w,
                        child: const Icon(
                          Icons.delete_forever_outlined,
                          color: Color(0xffFD6B6B),
                          size: 20,
                        ),
                      ).clickOnce(() {
                        // 释放资源
                        audioPlayerDispose(customAudio);
                        // 进行删除
                        widget.audioUrl.remove(customAudio.sourceUrl);
                        // final List<String> audioList = [];
                        // audioList.addAll(widget.audioUrl);
                        // audioList.remove(customAudio.sourceUrl);
                        playerList.remove(customAudio);
                        // if (widget.onCallBack != null) {
                        //   // 返回回调
                        //   widget.onCallBack!(audioList);
                        // }
                        setState(() {});
                      })
                    : SizedBox(width: 30.w)
              ],
            ),
          );
        },
        separatorBuilder: (context, index) {
          return AppGaps.vGap10;
        },
      ),
    );
  }
}

/// 自定义使用播放类
class CustomAudio {
  CustomAudio({required this.audioPlayer, required this.sourceUrl, this.maxDuration, this.position});

  /// 播放器
  AudioPlayer audioPlayer;

  /// 音频总时长
  Duration? maxDuration;

  /// 当前播放进度
  Duration? position;

  /// 音频地址
  String sourceUrl;
}
